package ui.swing.graphics.clock;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;

import javax.swing.JPanel;

public class ClockPanel extends JPanel {

	private static int RADIUS = 100;
	private static double MINUTE_HAND_LENGTH = 0.8 * RADIUS;
	private static double HOUR_HAND_LENGTH = 0.6 * RADIUS;

	private double totalMinutes = 0;

	public ClockPanel() {
		setPreferredSize(new Dimension(2 * RADIUS + 1, 2 * RADIUS + 1));
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);

		// draw the circular boundary
		Graphics2D g2 = (Graphics2D) g;
		Ellipse2D circle = new Ellipse2D.Double(0, 0, 2 * RADIUS, 2 * RADIUS);
		g2.draw(circle);

		// draw the hour hand
		double hourAngle = Math.toRadians(90 - 360 * totalMinutes / (12 * 60));
		drawHand(g2, hourAngle, HOUR_HAND_LENGTH);
		
		// draw the minute hand
		double minuteAngle = Math.toRadians(90 - 360 * totalMinutes / 60);
		drawHand(g2, minuteAngle, MINUTE_HAND_LENGTH);
	}

	private void drawHand(Graphics2D g2, double angle, double handLength) {
		Point2D end = new Point2D.Double(RADIUS + handLength * Math.cos(angle),
				RADIUS - handLength * Math.sin(angle));
		Point2D center = new Point2D.Double(RADIUS, RADIUS);
		g2.draw(new Line2D.Double(center, end));
	}
	
	public void setTime(int h, int m) {
		totalMinutes = h * 60 + m;
		repaint();
	}
}
